from io import BytesIO
from flask import make_response, current_app  # 添加 current_app 导入
import docx
from docx.shared import Inches, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn
from docx import Document
from datetime import datetime
from urllib.parse import quote
from database import get_db  # 新增：导入数据库连接工具
from bs4 import BeautifulSoup
import base64
import tempfile
import os
from .report_annual_emission import get_report_data as get_annual_emission_data
from .report_fuel_consumption import get_report_data as get_fuel_consumption_data
from .report_power import get_report_data as get_power_data
from .report_thermal import get_report_data as get_thermal_data
from docx.enum.section import WD_ORIENT


# 辅助函数：生成Word报告
def generate_word_report(data):
    # 创建Word文档对象
    doc = docx.Document()
    
    # 设置页面边距（1英寸 = 2.54厘米）
    sections = doc.sections
    for section in sections:
        section.top_margin = Inches(1.25)
        section.bottom_margin = Inches(1)
        section.left_margin = Inches(1.5)
        section.right_margin = Inches(1.5)
    
    # 添加封面内容
    # 1. 页眉国家标准编号
    国标段落 = doc.add_paragraph()
    国标段落.alignment = WD_ALIGN_PARAGRAPH.LEFT
    国标_run_bold = 国标段落.add_run('GB/T ')
    国标_run_normal = 国标段落.add_run('32151.29—2024')
    for run in [国标_run_bold, 国标_run_normal]:
        run.font.name = 'Microsoft YaHei'
        run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
        run.font.size = Pt(14)
    国标_run_bold.bold = True
    
    # 添加空行
    for _ in range(3):
        doc.add_paragraph('')
    
    # 2. 主标题
    标题段落 = doc.add_paragraph()
    标题段落.alignment = WD_ALIGN_PARAGRAPH.CENTER
    标题_run = 标题段落.add_run('机械设备制造企业温室气体排放报告')
    标题_run.font.name = 'Microsoft YaHei'
    标题_run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
    标题_run.font.size = Pt(18)
    标题_run.bold = False
    
    # 添加空行
    for _ in range(9):
        doc.add_paragraph('')
    
    # 3. 报告元数据
    主体段落 = doc.add_paragraph()
    主体段落.alignment = WD_ALIGN_PARAGRAPH.LEFT
    主体_run = 主体段落.add_run('报告主体（盖章）：')
    主体_run.font.name = 'Microsoft YaHei'
    主体_run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
    主体_run.font.size = Pt(14)
    主体_run.bold = False
    
    年度段落 = doc.add_paragraph()
    年度段落.alignment = WD_ALIGN_PARAGRAPH.LEFT
    年度_run = 年度段落.add_run(f'报告年度：{data.get("cover_data", {}).get("report_year", "2025")}')
    年度_run.font.name = 'Microsoft YaHei'
    年度_run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
    年度_run.font.size = Pt(14)
    年度_run.bold = False
    
    日期段落 = doc.add_paragraph()
    日期段落.alignment = WD_ALIGN_PARAGRAPH.LEFT
    当前日期 = datetime.now().strftime('%Y年%m月%d日')
    日期_run = 日期段落.add_run(f'编制日期：{当前日期}')
    日期_run.font.name = 'Microsoft YaHei'
    日期_run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
    日期_run.font.size = Pt(14)
    日期_run.bold = False

    # 添加分页符
    doc.add_page_break()

    # 第二页：添加企业基本信息表格
    try:
        db = get_db()
        cursor = db.cursor()
        
        # 1. 添加企业基本信息表格
        cursor.execute('SELECT entity_name, entity_type, unified_social_credit_code, industry, legal_representative, main_products, report_responsible_person, contact_information FROM report_tables ORDER BY id DESC LIMIT 1')
        basic_info = cursor.fetchone()
        
        if basic_info:
            # 添加表格标题 - 设置为微软雅黑、左对齐
            table_title = doc.add_heading('一、报告主体基本信息', level=1)
            table_title.alignment = WD_ALIGN_PARAGRAPH.LEFT  # 改为左对齐
            title_run = table_title.runs[0]
            title_run.font.name = 'Microsoft YaHei'
            title_run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
            title_run.font.size = Pt(14)  # 标题字体稍大
            
            # 创建表格 - 4行4列
            table = doc.add_table(rows=4, cols=4)
            table.style = 'Table Grid'
            
            # 设置表格自动调整以适应内容
            table.autofit = True
            
            # 定义表格数据
            table_data = [
                ('主体名称', basic_info['entity_name'] or ''),
                ('单位性质', basic_info['entity_type'] or ''),
                ('统一社会信用代码', basic_info['unified_social_credit_code'] or ''),
                ('所属行业', basic_info['industry'] or ''),
                ('法定代表人', basic_info['legal_representative'] or ''),
                ('主营产品', basic_info['main_products'] or ''),
                ('填报负责人', basic_info['report_responsible_person'] or ''),
                ('联系人信息', basic_info['contact_information'] or '')
            ]
            
            # 填充表格数据
            for i in range(4):
                row = i
                # 第一个字段（标签）
                table.rows[row].cells[0].text = table_data[i*2][0]
                # 第一个字段（值）
                table.rows[row].cells[1].text = table_data[i*2][1]
                # 第二个字段（标签）
                table.rows[row].cells[2].text = table_data[i*2+1][0]
                # 第二个字段（值）
                table.rows[row].cells[3].text = table_data[i*2+1][1]
            
            # 美化表格 - 设置字体和大小
            for row in table.rows:
                for cell in row.cells:
                    # 调整单元格宽度以适应内容
                    cell.width = Inches(1.5)  # 设置基础宽度
                    for paragraph in cell.paragraphs:
                        paragraph.alignment = WD_ALIGN_PARAGRAPH.LEFT  # 单元格内容左对齐
                        for run in paragraph.runs:
                            run.font.name = 'Microsoft YaHei'
                            run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
                            run.font.size = Pt(12)
            
            # 添加表格后的空行
            doc.add_paragraph()
        else:
            doc.add_paragraph('暂无企业基本信息数据')
        
        # 关闭数据库游标
        cursor.close()
    except Exception as e:
        # 确保游标被关闭
        if 'cursor' in locals():
            try:
                cursor.close()
            except:
                pass
        
        # 记录错误日志
        current_app.logger.error(f'添加企业基本信息表格失败: {str(e)}')
        
        # 向文档中添加错误信息
        error_paragraph = doc.add_paragraph(f'添加企业基本信息表格时出错: {str(e)}')
        error_run = error_paragraph.runs[0]
        error_run.font.name = 'Microsoft YaHei'
        error_run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
        error_run.font.size = Pt(12)
        error_run.font.color.rgb = RGBColor(255, 0, 0)  # 设置为红色

    # 添加分页符
    doc.add_page_break()

    #这里是插入的图片显示的位置
    try:
        # 从数据库获取图片信息
        db = get_db()
        cursor = db.cursor()
        cursor.execute('SELECT file_path, caption FROM report_images ORDER BY id ASC')
        images = cursor.fetchall()
        cursor.close()

        if images:
            # 添加图片标题
            images_title = doc.add_heading('图片展示', level=1)
            images_title.alignment = WD_ALIGN_PARAGRAPH.LEFT
            title_run = images_title.runs[0]
            title_run.font.name = 'Microsoft YaHei'
            title_run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
            title_run.font.size = Pt(14)

            for index, image in enumerate(images):
                # 图片文件路径
                image_path = os.path.join(current_app.root_path, image['file_path'])

                # 检查文件是否存在
                if os.path.exists(image_path):
                    # 添加图片段落
                    image_paragraph = doc.add_paragraph()
                    image_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

                    # 添加图片
                    doc.add_picture(image_path, width=Inches(5.0))  # 设置图片宽度

                    # 添加图片说明
                    if image['caption']:
                        caption_paragraph = doc.add_paragraph(f'图{index+1}: {image["caption"]}')
                        caption_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
                        caption_run = caption_paragraph.runs[0]
                        caption_run.font.name = 'Microsoft YaHei'
                        caption_run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
                        caption_run.font.size = Pt(12)

                    # 图片之间添加空行
                    doc.add_paragraph('')
                else:
                    # 添加图片不存在的提示
                    error_paragraph = doc.add_paragraph(f'图片不存在: {image["file_path"]}')
                    error_run = error_paragraph.runs[0]
                    error_run.font.name = 'Microsoft YaHei'
                    error_run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
                    error_run.font.size = Pt(12)
                    error_run.font.color.rgb = RGBColor(255, 0, 0)
    except Exception as e:
        current_app.logger.error(f'添加图片失败: {str(e)}')
        error_paragraph = doc.add_paragraph(f'添加图片时出错: {str(e)}')
        error_run = error_paragraph.runs[0]
        error_run.font.name = 'Microsoft YaHei'
        error_run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
        error_run.font.size = Pt(12)
        error_run.font.color.rgb = RGBColor(255, 0, 0)

    # 第二页：从数据库获取并添加段落信息
    try:
        db = get_db()
        cursor = db.cursor()
        # 执行查询：按display_order排序获取所有段落标题和内容
        cursor.execute('SELECT title, content, display_order FROM report_sections ORDER BY display_order ASC')
        sections = cursor.fetchall()
        cursor.close()
        
        # 添加段落标题
        content_title = doc.add_paragraph('报告内容')
        content_title.alignment = WD_ALIGN_PARAGRAPH.CENTER
        title_run = content_title.runs[0]
        title_run.font.name = 'Microsoft YaHei'
        title_run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
        title_run.font.size = Pt(16)
        title_run.bold = True
        doc.add_paragraph('')  # 添加空行
        
        # 循环添加段落内容
        for idx, section in enumerate(sections, 1):
            # 将sqlite3.Row对象转换为字典
            section_dict = dict(section)
            # 安全获取标题和内容（处理可能的空值）
            title = section_dict.get('title', '').strip()
            content = section_dict.get('content', '')

            # 添加标题（加粗，14pt，与正文格式区分）
            if title:
                title_para = doc.add_paragraph(f'{idx}. {title}')
                for run in title_para.runs:
                    run.font.name = 'Microsoft YaHei'
                    run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
                    run.font.size = Pt(14)
                    run.bold = True
                title_para.space_after = Pt(6)

            # 直接添加内容（不再解析HTML）
            if content:
                content_para = doc.add_paragraph(content)
                for run in content_para.runs:
                    run.font.name = 'Microsoft YaHei'
                    run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
                    run.font.size = Pt(12)
                # 设置正文段落格式（首行缩进）
                content_para.paragraph_format.first_line_indent = Pt(24)
                content_para.space_after = Pt(6)
    except Exception as e:
        # 添加错误提示段落
        error_para = doc.add_paragraph(f'获取段落信息失败: {str(e)}')
        error_run = error_para.runs[0]
        error_run.font.color.rgb = RGBColor(255, 0, 0)  # 红色错误文本
    # 添加分页符
    doc.add_page_break()
    # 第三部分：报表部分（第一个年度排放报表）
    selected_year = "2025"
    report_data = get_annual_emission_data(selected_year)

    output = BytesIO()
 
        
    title = doc.add_paragraph(f'{selected_year}年度温室气体排放量汇总表')
    title.alignment = WD_ALIGN_PARAGRAPH.CENTER
    title.runs[0].font.size = Pt(16)
    title.runs[0].bold = True
    title.runs[0].font.name = 'Microsoft YaHei'
    title.runs[0].font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
        
    table = doc.add_table(rows=1, cols=3)
    table.style = 'Table Grid'
        
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = '源类别'
    hdr_cells[1].text = '排放量(t)'
    hdr_cells[2].text = '排放量(tCO2e)'
    
    # 设置表头字体为微软雅黑、小四号(12pt)
    for cell in hdr_cells:
        for paragraph in cell.paragraphs:
            for run in paragraph.runs:
                run.font.name = 'Microsoft YaHei'
                run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
                run.font.size = Pt(12)
                run.bold = True
        
    # 添加数据行
    categories = [
        ('化石燃料燃烧CO2排放', 'fossil_fuel_t', 'fossil_fuel_tco2e'),
        ('CO2过程排放', 'process_co2_t', 'process_co2_tco2e'),
        ('HFCs过程排放', 'process_hfcs_t', 'process_hfcs_tco2e'),
        ('PFCs过程排放', 'process_pfcs_t', 'process_pfcs_tco2e'),
        ('SF6过程排放', 'process_sf6_t', 'process_sf6_tco2e'),
        ('购入电力产生的排放量', 'purchased_electricity_t', 'purchased_electricity_tco2e'),
        ('购入热力产生的排放量', 'purchased_heat_t', 'purchased_heat_tco2e'),
        ('输出电力产生的排放量', 'exported_electricity_t', 'exported_electricity_tco2e'),
        ('输出热力产生的排放量', 'exported_heat_t', 'exported_heat_tco2e'),
        # 修改字段名称以匹配模板文件中的命名
        ('企业温室气体排放总量(不包括购入和输出的电力、热力)', '', 'total_emission_exclude_energy_tco2e'),
        ('企业温室气体排放总量(包括购入和输出的电力、热力)', '', 'total_emission_include_energy_tco2e')
    ]
        
    for category, t_key, tco2e_key in categories:
        row = table.add_row().cells
        row[0].text = category
        
        # 设置单元格字体为微软雅黑、小四号(12pt)
        for cell in row:
            for paragraph in cell.paragraphs:
                for run in paragraph.runs:
                    run.font.name = 'Microsoft YaHei'
                    run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
                    run.font.size = Pt(12)
        
        # 处理没有对应t字段的情况
        if t_key and report_data.get(t_key) is not None:
            row[1].text = f"{report_data[t_key]:.4f}"  # 修复f-string语法并保留4位小数
        else:
            row[1].text = '0.0000'
        
        # 确保使用正确的tco2e字段名称并格式化
        if report_data.get(tco2e_key) is not None:
            row[2].text = f"{report_data[tco2e_key]:.4f}"  # 格式化保留4位小数
        else:
            row[2].text = '0.0000'
        
    # 第三部分：报表部分（第2个燃料消耗报表）
    # 添加分页符
    doc.add_page_break()

    # 获取燃料消耗数据
    fuel_data = get_fuel_consumption_data(selected_year)
    
    # 添加报表标题
    fuel_title = doc.add_paragraph('化石燃料燃烧的活动数据和排放因子数据一览表（通用）')
    fuel_title.alignment = WD_ALIGN_PARAGRAPH.CENTER
    fuel_title.runs[0].font.size = Pt(16)
    fuel_title.runs[0].bold = True
    fuel_title.runs[0].font.name = 'Microsoft YaHei'
    fuel_title.runs[0].font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
    
    # 创建表格（纵向排列，保持7列）
    if fuel_data:
        fuel_table = doc.add_table(rows=len(fuel_data) + 1, cols=7)
        fuel_table.style = 'Table Grid'
        
        # 设置表头
        hdr_cells = fuel_table.rows[0].cells
        hdr_cells[0].text = '燃料品类'
        hdr_cells[1].text = '消费量(t)'
        hdr_cells[2].text = '低位发热量GJ/t或GJ/10⁴m³数据'
        hdr_cells[3].text = '发热量数据来源'
        hdr_cells[4].text = '单位热值含碳量10⁻³tC/GJ'
        hdr_cells[5].text = '碳氧化率%'
        hdr_cells[6].text = '碳氧化率数据来源'
        
        # 设置表头样式
        for cell in hdr_cells:
            for paragraph in cell.paragraphs:
                for run in paragraph.runs:
                    run.bold = True
                    run.font.name = 'Microsoft YaHei'
                    run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
                    run.font.size = Pt(12)
        
        # 添加数据行
        for idx, item in enumerate(fuel_data):
            row_cells = fuel_table.rows[idx + 1].cells
            row_cells[0].text = item['fuel_type']
            row_cells[1].text = f"{item['consumption']:.4f}"
            row_cells[2].text = f"{item['low_calorific_value']:.4f}"
            row_cells[3].text = f"{item['calorific_source']}"
            row_cells[4].text = f"{item['carbon_content']:.4f}"
            row_cells[5].text = f"{item['oxidation_rate']:.4f}%"
            row_cells[6].text = f"{item['oxidation_source']}"
            
            # 设置数据行样式
            for cell in row_cells:
                for paragraph in cell.paragraphs:
                    for run in paragraph.runs:
                        run.font.name = 'Microsoft YaHei'
                        run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
                        run.font.size = Pt(12)
    
    # 第三部分：报表部分（第3个输入输出电力活动数据和排放因子数据一览表）
    # 添加分页符
    doc.add_page_break()

     # 获取电力活动数据
    power_data = get_power_data(selected_year)

    # 添加报表标题
    power_title = doc.add_paragraph('输入输出电力活动数据和排放因子数据一览表')
    power_title.alignment = WD_ALIGN_PARAGRAPH.CENTER
    power_title.runs[0].font.size = Pt(16)
    power_title.runs[0].bold = True
    power_title.runs[0].font.name = 'Microsoft YaHei'
    power_title.runs[0].font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')  

    # 创建表格
    if power_data:
        power_table = doc.add_table(rows=1, cols=4)
        power_table.style = 'Table Grid'

        # 设置表头
        hdr_cells = power_table.rows[0].cells
        hdr_cells[0].text = '项目'
        hdr_cells[1].text = '电量(MWh)'
        hdr_cells[2].text = '排放因子(tCO₂/MWh)'
        hdr_cells[3].text = '排放量(tCO₂)'

        # 设置表头样式
        for cell in hdr_cells:
            for paragraph in cell.paragraphs:
                for run in paragraph.runs:
                    run.bold = True
                    run.font.name = 'Microsoft YaHei'
                    run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
                    run.font.size = Pt(12)

        # 填充数据
        # 初始化购入和输出数据变量
        purchase_mwh_total = 0.0
        purchase_emission_total = 0.0
        purchase_factor = None

        output_mwh_total = 0.0
        output_emission_total = 0.0
        output_factor = None

        # 遍历所有数据，累加购入和输出数据
        for item in power_data:
            # 处理购入数据
            if item.get('purchase_mwh') is not None:
                purchase_mwh_total += float(item.get('purchase_mwh', 0))
                purchase_emission_total += float(item.get('purchase_emission', 0))
                if purchase_factor is None:
                    purchase_factor = item.get('purchase_factor', '')

            # 处理输出数据
            if item.get('output_mwh') is not None:
                output_mwh_total += float(item.get('output_mwh', 0))
                output_emission_total += float(item.get('output_emission', 0))
                if output_factor is None:
                    output_factor = item.get('output_factor', '')

        # 添加购入数据行（如果有数据）
        if purchase_mwh_total > 0:
            row = power_table.add_row().cells
            row[0].text = '购入合计'
            row[1].text = f"{purchase_mwh_total:.4f}"
            row[2].text = f"{purchase_factor}"
            row[3].text = f"{purchase_emission_total:.4f}"

            # 设置数据行样式
            for cell in row:
                for paragraph in cell.paragraphs:
                    for run in paragraph.runs:
                        run.font.name = 'Microsoft YaHei'
                        run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
                        run.font.size = Pt(12)

        # 添加输出数据行（如果有数据）
        if output_mwh_total > 0:
            row = power_table.add_row().cells
            row[0].text = '输出合计'
            row[1].text = f"{output_mwh_total:.4f}"
            row[2].text = f"{output_factor}"
            row[3].text = f"{output_emission_total:.4f}"

            # 设置数据行样式
            for cell in row:
                for paragraph in cell.paragraphs:
                    for run in paragraph.runs:
                        run.font.name = 'Microsoft YaHei'
                        run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
                        run.font.size = Pt(12)

 

    # 第四部分：报表部分（第4个输入输出热力活动数据和排放因子数据一览表）
    # 添加分页符
    doc.add_page_break()
    # 获取热力活动数据
    thermal_data = get_thermal_data(selected_year)
    
    # 添加报表标题
    thermal_title = doc.add_paragraph('输入输出热力活动数据和排放因子数据一览表')
    thermal_title.alignment = WD_ALIGN_PARAGRAPH.CENTER
    thermal_title.runs[0].font.size = Pt(16)
    thermal_title.runs[0].bold = True
    thermal_title.runs[0].font.name = 'Microsoft YaHei'
    thermal_title.runs[0].font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
    
    # 创建表格
    if thermal_data:
        thermal_table = doc.add_table(rows=1, cols=4)
        thermal_table.style = 'Table Grid'
        
        # 设置表头
        hdr_cells = thermal_table.rows[0].cells
        hdr_cells[0].text = '类型'
        hdr_cells[1].text = '活动数据(GJ)'
        hdr_cells[2].text = '排放因子(tCO₂/GJ)'
        hdr_cells[3].text = '排放量(tCO₂e)'
        
        # 设置表头样式
        for cell in hdr_cells:
            for paragraph in cell.paragraphs:
                for run in paragraph.runs:
                    run.bold = True
                    run.font.name = 'Microsoft YaHei'
                    run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
                    run.font.size = Pt(12)
        
        # 初始化购入和输出热力数据变量
        purchase_activity_total = 0.0
        purchase_emission_total = 0.0
        purchase_factor = None

        output_activity_total = 0.0
        output_emission_total = 0.0
        output_factor = None

        # 遍历所有数据，累加购入和输出数据
        for item in thermal_data:
            # 处理购入热力数据
            purchase_gj = item.get('purchase_gj')
            purchase_activity_total += float(purchase_gj) if purchase_gj is not None else 0
            purchase_emission = item.get('purchase_emission')
            purchase_emission_total += float(purchase_emission) if purchase_emission is not None else 0
            if purchase_factor is None:
                purchase_factor = item.get('purchase_factor', '')

            # 处理输出热力数据
            output_gj = item.get('output_gj')
            output_activity_total += float(output_gj) if output_gj is not None else 0
            output_emission = item.get('output_emission')
            output_emission_total += float(output_emission) if output_emission is not None else 0
            if output_factor is None:
                output_factor = item.get('output_factor', '')

        # 添加购入热力数据行（无论是否有数据）
        row = thermal_table.add_row().cells
        row[0].text = '购入合计'
        row[1].text = f"{purchase_activity_total:.4f}"
        row[2].text = f"{purchase_factor}"
        row[3].text = f"{purchase_emission_total:.4f}"

        # 设置数据行样式
        for cell in row:
            for paragraph in cell.paragraphs:
                for run in paragraph.runs:
                    run.font.name = 'Microsoft YaHei'
                    run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
                    run.font.size = Pt(12)

        # 添加输出热力数据行（无论是否有数据）
        row = thermal_table.add_row().cells
        row[0].text = '输出合计'
        row[1].text = f"{output_activity_total:.4f}"
        row[2].text = f"{output_factor}"
        row[3].text = f"{output_emission_total:.4f}"

        # 设置数据行样式
        for cell in row:
            for paragraph in cell.paragraphs:
                for run in paragraph.runs:
                    run.font.name = 'Microsoft YaHei'
                    run.font.element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
                    run.font.size = Pt(12)
    
    # 保存到内存缓冲区
    output = BytesIO()
    doc.save(output)
    output.seek(0)
    
    # 准备响应 - 处理中文文件名
    filename = f'碳排放报告_{data.get("cover_data", {}).get("report_year", "")}.docx'
    encoded_filename = quote(filename.encode('utf-8'))
    
    response = make_response(output.getvalue())
    response.headers['Content-Type'] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    response.headers['Content-Disposition'] = f'attachment; filename*=UTF-8''{encoded_filename}'''
    return response
